package com.example.admin_beautiful.filter;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.admin_beautiful.wrapper.RequestWrapper;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.Arrays;
import java.util.List;

/**
 * 过滤器，@WebFilter(urlPatterns = "/*")：过滤所有请求
 */
@WebFilter(urlPatterns = "/api/*")
public class MyFilter implements Filter {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

//    白名单
    private static final String NOT_FILTER_STR = "/api/account/getRegister|";
    private static List<String> NOTFILTER_ARRAY;
    public MyFilter() {
        NOTFILTER_ARRAY = Arrays.asList(NOT_FILTER_STR.split("\\|"));
    }

    /**
     * 初始化
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /**
     * 请求处理，@SneakyThrows：抛出异常
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     */
    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain){
        //转换自己的wrapper，实现多次读写
        RequestWrapper request = new RequestWrapper((HttpServletRequest) servletRequest);
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //请求GET/POST
        String method = request.getMethod();
        String getUrl = request.getRequestURI();
        System.out.println("getRequestURI---->"+getUrl);
        //获取请求头
        String authorization = request.getHeader("Authorization");
        //开放开发者
        if(authorization.equals("admin")){
            filterChain.doFilter(request, servletResponse);
            return;
        }

//        开放GET接口
        if(method.equals("GET")){
            filterChain.doFilter(request, servletResponse);
            return;
        }

        String value = stringRedisTemplate.opsForValue().get("user_token:"+authorization);
        if(value == null){
            if(!NOTFILTER_ARRAY.contains(getUrl)){
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "认证失败");
                return;
            }
        }
        //取得body数据
        BufferedReader bufferedReader = request.getReader();
        String line;
        StringBuilder builder = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null){
            builder.append(line);
        }
        String builderString = builder.toString();
        System.out.println("前端数据："+builderString);

        JSONObject jsonObject = JSON.parseObject(builderString);
        //重置json请求体，保证下游业务无感知获取数据
        request.setBody(jsonObject.toJSONString().getBytes());

        filterChain.doFilter(request, servletResponse);

    }

    /**
     * 清理资源
     */
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
